package ezXpns.GUI.controllers;

import java.util.Date;
import java.util.HashMap;

import org.apache.commons.lang3.tuple.Pair;

import ezXpns.BudgetChange;
import ezXpns.Report;
import ezXpns.GUI.AnalysisGUIPanel;
import ezXpns.analysis.AggregationResultHandler;
import ezXpns.analysis.AggregationTask;
import ezXpns.analysis.aggregators.Sum;
import ezXpns.analysis.aggregators.TagSum;
import ezXpns.analysis.aggregators.TypeSum;
import ezXpns.analysis.transforms.AmountExtractor;
import ezXpns.analysis.transforms.TagExtractor;
import ezXpns.analysis.transforms.TypeExtractor;
import ezXpns.storage.Query;
import ezXpns.storage.Storage;
import ezXpns.storage.queries.DateRangeQuery;

/**
 * @author A0086931X
 */

//@author A0086931X
public class ReportController {
	public ReportController(Storage<BudgetChange> expenseStorage, Storage<BudgetChange> incomeStorage,
			AnalysisGUIPanel gui) {

		this.gui = gui;
		this.expenseStorage = expenseStorage;
		this.incomeStorage = incomeStorage;
	}

	public void requestAnalysis(Pair<Date, Date> range) {

		Query<BudgetChange> query = new DateRangeQuery(range.getLeft(), range.getRight());

		gui.refreshReport(newView(query, true));
	}

	public void setReportSource(BuiltinReportSource source) {

	}

	private Report newView(Query<BudgetChange> query, boolean addable) {
		report = new Report();

		expenseStorage.liveQueryMulti(query, AggregationTask.create(new AmountExtractor(), new Sum(),
				new AggregationResultHandler<Float>() {
					@Override
					public void onNewValue(Float value) {
						report.setTotalExpense(value);
					}
				}), AggregationTask.create(new TypeExtractor(), new TypeSum(),
				new AggregationResultHandler<HashMap<String, Float>>() {
					@Override
					public void onNewValue(HashMap<String, Float> entry) {
						report.setExpenseHash(entry);
					}
				}), AggregationTask.create(new TagExtractor(), new TagSum(),
				new AggregationResultHandler<HashMap<String, Float>>() {
					@Override
					public void onNewValue(HashMap<String, Float> entry) {
						report.setTagHash(entry);
					}
				}));

		incomeStorage.liveQueryMulti(query,
				AggregationTask.create(new AmountExtractor(), new Sum(), new AggregationResultHandler<Float>() {
					@Override
					public void onNewValue(Float value) {
						report.setTotalIncome(value);
					}
				}));

		return report;
	}

	private Report report;
	private Storage<BudgetChange> expenseStorage;
	private Storage<BudgetChange> incomeStorage;

	private AnalysisGUIPanel gui;
}
